<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>欢迎登录</h2>
        <p>健研社</p>
      </div>

      <el-tabs v-model="activeTab" class="login-tabs">
        <!-- 密码登录 -->
        <el-tab-pane label="密码登录" name="password">
          <el-form
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            class="login-form"
            @keyup.enter="handleLogin"
          >
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                placeholder="请输入用户名"
                size="large"
                clearable
              >
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                size="large"
                show-password
                clearable
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                size="large"
                :loading="loading"
                class="login-button"
                @click="handleLogin"
              >
                {{ loading ? '登录中...' : '登录' }}
              </el-button>
            </el-form-item>
          </el-form>

          <div class="login-footer">
            <span class="register-link" @click="showRegister = true">
              还没有账号？立即注册
            </span>
          </div>
        </el-tab-pane>

        <!-- 钉钉登录 -->
        <el-tab-pane label="钉钉登录" name="dingtalk">
          <div class="dingtalk-login">
            <div class="dingtalk-icon-wrapper">
              <svg class="dingtalk-logo" viewBox="0 0 1024 1024" width="64" height="64">
                <path fill="#0089FF" d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64z m238.8 449.8c-26.3 11.4-64.5 23.5-113.5 35.2-18.5 4.4-35.5 7.5-50.8 9.5-6.3 0.8-12.3 1.4-18 1.8-89.8 6.6-127.8-7.5-142.3-38.3-9.5-20.3-6.8-44.3 7.5-67.5 3.8-6.1 8.3-11.4 13.3-15.8-56.3 11.4-99 27.3-127.5 47.3-42 29.3-63 67.5-63 113.8 0 36 12.8 66 38.3 90 37.5 35.3 98.3 53.3 181.5 53.3 54.8 0 108.8-9 160.5-26.3 71.3-23.3 128.3-56.3 170.3-98.3 39-39 58.5-81 58.5-125.3 0-11.3-1.5-22.5-4.5-33.8-23.3 18.8-54.8 37.5-94.5 56.3l-15.8 0.8z"/>
              </svg>
            </div>
            
            <h3 class="dingtalk-title">钉钉扫码登录</h3>
            <p class="dingtalk-desc">使用钉钉扫一扫，快速完成登录</p>
            
            <el-button
              type="primary"
              size="large"
              :loading="dingtalkLoading"
              class="dingtalk-button"
              @click="handleDingtalkLogin"
            >
              <span v-if="!dingtalkLoading">开始扫码登录</span>
              <span v-else>正在跳转...</span>
            </el-button>
            
            <div class="dingtalk-features">
              <div class="feature-item">
                <el-icon><Check /></el-icon>
                <span>安全可靠</span>
              </div>
              <div class="feature-item">
                <el-icon><Check /></el-icon>
                <span>快速便捷</span>
              </div>
              <div class="feature-item">
                <el-icon><Check /></el-icon>
                <span>企业认证</span>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 注册对话框 -->
    <el-dialog
      v-model="showRegister"
      title="用户注册"
      width="90%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="3-64个字符，字母数字下划线"
            clearable
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="至少6个字符"
            show-password
            clearable
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="再次输入密码"
            show-password
            clearable
          />
        </el-form-item>

        <el-form-item label="身份证照片" prop="image_url">
          <div class="idcard-upload-wrapper">
            <el-upload
              class="idcard-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleIdCardSuccess"
              :before-upload="beforeIdCardUpload"
              :data="uploadData"
              :loading="ocrLoading"
            >
              <img v-if="registerForm.image_url" :src="registerForm.image_url" class="idcard-preview" />
              <div v-else class="upload-placeholder">
                <el-icon class="idcard-uploader-icon"><Plus /></el-icon>
                <div class="upload-text">上传身份证照片</div>
              </div>
            </el-upload>
            <div class="upload-tip">上传身份证后将自动识别并填充信息</div>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showRegister = false">取消</el-button>
        <el-button
          type="primary"
          :loading="registerLoading"
          @click="handleRegister"
        >
          注册
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Check, Plus } from '@element-plus/icons-vue'
import { login, register, getDingtalkLoginUrl } from '@/api/user'
import { getQiniuToken, recognizeIdCard } from '@/api/verify'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

// 当前标签页
const activeTab = ref('password')

// 登录表单
const loginFormRef = ref(null)
const loginForm = reactive({
  username: '',
  password: ''
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 64, message: '用户名长度为3-64个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '只能包含字母、数字、下划线', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码至少6个字符', trigger: 'blur' }
  ]
}

const loading = ref(false)

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  await loginFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    loading.value = true
    try {
      const response = await login({
        username: loginForm.username,
        password: loginForm.password
      })
      
      // 保存 token 和用户信息
      userStore.setToken(response.token, response.refresh_token)
      userStore.setUserInfo(response.user)
      localStorage.setItem('userInfo', JSON.stringify(response.user))
      
      ElMessage.success('登录成功！')
      
      // 跳转到首页
      router.push('/')
    } catch (error) {
      console.error('登录失败:', error)
    } finally {
      loading.value = false
    }
  })
}

// 注册相关
const showRegister = ref(false)
const registerFormRef = ref(null)
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  image_url: ''
})

const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 64, message: '用户名长度为3-64个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '只能包含字母、数字、下划线', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码至少6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

const registerLoading = ref(false)

// 七牛云上传相关
const qiniuToken = ref('')
const uploadData = ref({ token: '' })
const uploadUrl = 'https://up-z2.qiniup.com/' // 七牛云华南区
const ocrLoading = ref(false) // OCR识别加载状态

// 获取七牛云Token
const fetchQiniuToken = async () => {
  try {
    const response = await getQiniuToken()
    if (response.data) {
      qiniuToken.value = response.data
    } else if (response.token) {
      qiniuToken.value = response.token
    } else {
      qiniuToken.value = response
    }
    uploadData.value.token = qiniuToken.value
    console.log('获取七牛云token成功')
  } catch (error) {
    console.error('获取七牛云token失败:', error)
    ElMessage.warning('获取上传凭证失败，身份证上传功能暂时不可用')
  }
}

// 上传前的校验
const beforeIdCardUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  
  if (!qiniuToken.value) {
    ElMessage.error('上传凭证未获取，请刷新页面重试')
    return false
  }
  
  return true
}

// 上传成功后的处理 - 调用OCR识别
const handleIdCardSuccess = async (res) => {
  console.log('身份证上传成功:', res)
  // 图片URL - 优先使用七牛云返回的url，如果没有则手动拼接
  const imgUrl = res.url || `http://t4vs0af42.hn-bkt.clouddn.com/${res.key}`
  registerForm.image_url = imgUrl
  
  ElMessage.success('身份证上传成功，正在识别...')
  
  // 调用OCR识别接口
  ocrLoading.value = true
  try {
    const ocrResult = await recognizeIdCard(imgUrl)
    console.log('OCR识别结果:', ocrResult)
    
    // 处理返回的提示文本或实际识别数据
    if (ocrResult && ocrResult.code === 200) {
      if (typeof ocrResult.data === 'string') {
        // 返回的是提示文本
        ElMessage.success(ocrResult.data)
        console.log('服务器提示:', ocrResult.data)
      } else if (ocrResult.data && (ocrResult.data.name || ocrResult.data.idcard_number)) {
        // 实际识别数据
        const { name, idcard_number } = ocrResult.data
        
        // 自动填充用户名（使用真实姓名）
        if (name) {
          registerForm.username = name
          ElMessage.success(`识别成功！姓名：${name}`)
        }
        
        // 可以添加更多字段的自动填充
        if (idcard_number) {
          console.log('身份证号:', idcard_number)
        }
      }
    } else {
      ElMessage.warning('身份证识别失败，请手动填写用户名')
    }
  } catch (error) {
    console.error('OCR识别失败:', error)
    ElMessage.error('身份证识别失败，请手动填写用户名')
  } finally {
    ocrLoading.value = false
  }
}

// 注册处理
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  await registerFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    registerLoading.value = true
    try {
      await register({
        username: registerForm.username,
        password: registerForm.password,
        image_url: registerForm.image_url || ''  // 如果没有填写，传空字符串
      })
      
      ElMessage.success('注册成功！请登录')
      showRegister.value = false
      
      // 保存用户名用于自动填充
      const savedUsername = registerForm.username
      
      // 清空注册表单
      registerForm.username = ''
      registerForm.password = ''
      registerForm.confirmPassword = ''
      registerForm.image_url = ''
      registerFormRef.value.resetFields()
      
      // 自动填充登录表单
      loginForm.username = savedUsername
    } catch (error) {
      console.error('注册失败:', error)
    } finally {
      registerLoading.value = false
    }
  })
}

// 钉钉登录
const dingtalkLoading = ref(false)

const handleDingtalkLogin = async () => {
  dingtalkLoading.value = true
  try {
    const response = await getDingtalkLoginUrl()
    // 跳转到钉钉授权页面
    window.location.href = response.url
  } catch (error) {
    console.error('获取钉钉登录URL失败:', error)
    ElMessage.error('获取钉钉登录URL失败，请稍后重试')
  } finally {
    dingtalkLoading.value = false
  }
}

// 监听注册对话框的打开，自动获取七牛云token
watch(showRegister, (newValue) => {
  if (newValue) {
    fetchQiniuToken()
  }
})
</script>

<style scoped>
.login-container {
  min-height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  padding: 20px 16px;
}

.login-box {
  width: 100%;
  max-width: 100%;
  background: white;
  border-radius: 12px;
  padding: 32px 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  font-size: 24px;
  color: #303133;
  margin: 0 0 8px 0;
  font-weight: 500;
}

.login-header p {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.login-tabs {
  margin-bottom: 20px;
}

.login-form {
  margin-top: 30px;
  min-height: 220px;
}

.login-button {
  width: 100%;
  height: 44px;
  font-size: 15px;
}

.login-footer {
  text-align: center;
  margin-top: 20px;
  min-height: 24px;
}

.register-link {
  color: #409eff;
  cursor: pointer;
  font-size: 14px;
  transition: color 0.3s;
}

.register-link:hover {
  color: #66b1ff;
}

.dingtalk-login {
  text-align: center;
  margin-top: 30px;
  min-height: 220px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.dingtalk-login > * {
  flex-shrink: 0;
}

.dingtalk-icon-wrapper {
  margin-bottom: 16px;
  animation: float 3s ease-in-out infinite;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-8px);
  }
}

.dingtalk-logo {
  filter: drop-shadow(0 4px 12px rgba(0, 137, 255, 0.2));
}

.dingtalk-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 0 0 6px 0;
}

.dingtalk-desc {
  font-size: 13px;
  color: #909399;
  margin: 0 0 20px 0;
}

.dingtalk-button {
  width: 100%;
  height: 44px;
  font-size: 15px;
  background-color: #0089ff;
  border-color: #0089ff;
  font-weight: 500;
  letter-spacing: 0.5px;
  transition: all 0.3s;
}

.dingtalk-button:hover {
  background-color: #0076db;
  border-color: #0076db;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 137, 255, 0.3);
}

.dingtalk-features {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #606266;
}

.feature-item .el-icon {
  color: #67c23a;
  font-size: 14px;
}

/* 身份证上传样式 */
.idcard-upload-wrapper {
  width: 100%;
}

.idcard-uploader {
  width: 100%;
  display: flex;
  justify-content: center;
}

:deep(.idcard-uploader .el-upload) {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
  width: 280px;
  height: 180px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
}

:deep(.idcard-uploader .el-upload:hover) {
  border-color: #409eff;
  background-color: #f5f7fa;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.idcard-uploader-icon {
  font-size: 48px;
  color: #8c939d;
}

.upload-text {
  font-size: 14px;
  color: #606266;
}

.idcard-preview {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: contain;
  border-radius: 6px;
}

.upload-tip {
  text-align: center;
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

/* 响应式 - 身份证上传 */
@media (max-width: 768px) {
  :deep(.idcard-uploader .el-upload) {
    width: 100%;
    height: 160px;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-box {
    padding: 30px 20px;
  }

  .login-header h2 {
    font-size: 22px;
  }
}
</style>